#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：zhcx-service-test 
@File    ：listing_grading_public_way.py
@Author  ：关依林
@Date    ：2023/8/7 18:33
'''
import datetime
import json
import os
from testcases.ProductGrading_Strategy.AmazonListing.dao.query_sql_method import *
from common.setting import ensure_path_sep
from testcases.ProductGrading_Strategy.test001 import *

filePath = ensure_path_sep("\\config\\config.yaml")


# 连接Java项目获取游标
def connectMysql(dbName):
    """

    @param sql:
    @return:
    """
    cursor = DB(filePath, dbName)
    return cursor


# def connectMongo(collName):
#     """
#
#     @param sql:
#     @return:
#     """
#     uri = "mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin"
#     dbName = "test_zhcxkj_java_center"
#     collName = collName
#     cursor = MongoDBLink(uri, dbName, collName)
#     return cursor


# 获取模板规则
def getTemplateCondition(templateId):
    """

    @param templateId:
    @return:
    """

    sql = f"SELECT condition_field, condition_value FROM t_template_condition WHERE template_id = {templateId}"
    condition = connectMysql("Java_centerStrategy_Test").execute_sql_many(sql)
    return condition


# 获取模板规则
def getTemplateConditionTest(templateId):
    """

    @param templateId:
    @return:
    """

    sql = f"SELECT condition_field, condition_value FROM t_template_condition WHERE template_id = {templateId}"
    condition = connectMysql("Java_centerStrategy_Test").execute_sql_many(sql)
    return condition


# # Mongo连接策略、模板与sku关联表
# def connectMongo(collName):
#     """
#
#     @param collName:
#     @return:
#     """
#     uri = "mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin"
#     dbName = "zhcxkj_java_center"
#     cursor = MongoDBLink(uri, dbName, collName)
#     return cursor


# Listing分表计算逻辑
def getListingBaseId(orderSourceId):
    """

    @param ordersourceId:
    @return:
    """
    id = orderSourceId % 32 + 1
    return id


def getTemplateExecute(templateRule):
    filedType1 = []
    filedType2 = []
    filedType3 = []
    templateRuleValue1 = []
    templateRuleValue2 = []
    templateRuleValue3 = []

    for condition in templateRule:
        filedName = condition["condition_field"]

        if getListingTypeTemplatecondition(filedName):

            if filedName == "online_status":
                templateRuleValue1.append({filedName: eval(condition["condition_value"])["value"]})
                filedType1.append("status")

            elif filedName == "fba_new":
                filedType1.append("asin_first_arrival_time")
                filedType1.append("first_arrival_time")
                templateRuleValue1.append({filedName: eval(condition["condition_value"])["value"]})

            elif filedName == "business_user_name":
                filedType1.append("listing_person_id")
                filedType1.append("business_user_id")
                templateRuleValue1.append({filedName: eval(condition["condition_value"])["value"]})

            elif filedName == "available_quantity":
                filedType1.append("quality")
                templateRuleValue1.append({filedName: eval(condition["condition_value"])})

            elif filedName == "holiday_tag":
                filedType1.append("tag_id")
                templateRuleValue1.append({filedName: eval(condition["condition_value"])["value"]})

            elif filedName == "sale_price":
                filedType1.append(filedName)
                templateRuleValue1.append({filedName: eval(condition["condition_value"])})
            elif filedName == "trans_to_fba_time":
                filedType1.append(filedName)
                templateRuleValue1.append({filedName: eval(condition["condition_value"])})
            elif filedName == "trans_to_fba_pending_time":
                filedType1.append(filedName)
                templateRuleValue1.append({filedName: eval(condition["condition_value"])})
            elif filedName == "publish_time":
                filedType1.append(filedName)
                templateRuleValue1.append({filedName: eval(condition["condition_value"])})
            elif filedName == "listing_person":
                filedType1.append("listing_person_id")
                templateRuleValue1.append({filedName: eval(condition["condition_value"])})
            else:
                filedType1.append(filedName)
                templateRuleValue1.append({filedName: eval(condition["condition_value"])["value"]})

        elif getListingTypeTemplateconditionOther(filedName):

            if filedName == "wait_to_fba_state":
                filedType3.append("wait_to_fba_type")
                templateRuleValue3.append({"wait_to_fba_type": eval(condition["condition_value"])["value"]})

            elif filedName == "profit_rate":
                filedType3.append("month_avg_profits")
                templateRuleValue3.append({filedName: eval(condition["condition_value"])})

        else:

            if filedName == "holiday_tag":
                filedType2.append("tag_id")
                templateRuleValue2.append({filedName: eval(condition["condition_value"])["value"]})

            elif filedName == "rating_start":
                filedType2.append("rating_star")
                templateRuleValue2.append({filedName: eval(condition["condition_value"])})

            else:
                filedType3.append(filedName)

    return [filedType1, filedType2, filedType3], [templateRuleValue1, templateRuleValue2, templateRuleValue3]


def templateRulePack(templateRule):
    filedType = []
    filedTypeOther = []
    templateRuleValue = []
    templateRuleValueOther = []
    for condition in templateRule:
        filedName = condition["condition_field"]
        if filedName in [
            "first_arrival_time",
            "asin_first_arrival_time"
        ]:
            filedType.append(filedName)
            templateRuleValue.append({filedName: condition["condition_value"]})
        elif filedName in [
            "estimate_sale_num",
            "available_day",
            "fba_inventory",
            "inventory_age",
            "receiving_time"
        ]:
            filedTypeOther.append(filedName)
            templateRuleValueOther.append({filedName: condition["condition_value"]})
    return [filedType, filedTypeOther], [templateRuleValue, templateRuleValueOther]


def orderTemplateRulePack(templateRule):
    filedType = []
    filedTypeOther = []
    templateRuleValue = []
    templateRuleValueOther = []
    for condition in templateRule:
        filedName = condition["condition_field"]
        if filedName in [
            "asin_first_order_time",
            "first_order_time",
            "sale_num"
        ]:
            filedType.append(filedName)
            templateRuleValue.append(condition)
        else:
            filedTypeOther.append(filedName)
            templateRuleValueOther.append(condition)
    return [filedType, filedTypeOther], [templateRuleValue, templateRuleValueOther]


def convertFiled(filedName):
    """

    @param filedName:
    @return:
    """
    if getListingTypeTemplatecondition(filedName):
        if filedName == "online_status":
            return "status"
        elif filedName == "fba_new":
            return ["asin_first_arrival_time", "first_arrival_time"]
        elif filedName == "business_user_name":
            return ["listing_person", "business_user_name"]
        elif filedName == "available_quantity":
            return "quality"
        elif filedName == "holiday_tag":
            return "tag_id"
        else:
            return filedName
    elif getListingTypeTemplateconditionOther(filedName):
        if filedName == "wait_to_fba_state":
            return "wait_to_fba_type"
        elif filedName == "profit_rate":
            return "month_avg_profits"
    else:
        if filedName == "holiday_tag":
            return "tag_id"
        else:
            return filedName


def convertValueType(value):
    if type(value) == int:
        value = [value]
    return value


def mediumTemplateData(count, matchingSku, tempMatchingSku):
    if count:
        matchingSku = tuple(set(matchingSku) & set(tempMatchingSku))
    else:
        matchingSku = tempMatchingSku
    return matchingSku


def getSliceMskuAsinData(id, cursor, data):
    sql = f"SELECT msku, asin FROM " \
          f"t_amazon_listing_{id} WHERE id IN {data}"
    res = cursor.execute_sql_many(sql)
    return res


def getSliceData2(id, cursor, data):
    sql = f"SELECT source_id, msku, asin FROM " \
          f"t_amazon_listing_{id} WHERE id IN {data}"
    res = cursor.execute_sql_many(sql)
    return res


def filterCondition1(sliceData, templateRuleValue, cursorData):
    """

    @param res
    @param conditionName:
    @param condition:
    @return:
    """
    sliceData = sliceData
    for condition in templateRuleValue:
        conditionKey = ','.join(condition.keys())
        if "online_status" == conditionKey:
            value = convertValueType(condition["online_status"])
            sliceData = list(filter(lambda x: x["status"] in value, sliceData))
            continue

        if "delivery_type" == conditionKey:
            value = convertValueType(condition["delivery_type"])
            sliceData = list(filter(lambda x: x["delivery_type"] in value, sliceData))
            continue

        if "listing_method" == conditionKey:
            value = convertValueType(condition["listing_method"])
            if 0 in value and None not in value:
                value.append(None)
            sliceData = list(filter(lambda x: x["listing_method"] in value, sliceData))
            continue

        if "fba_new" == conditionKey:
            value = convertValueType(condition["fba_new"])
            sliceData = list(
                filter(lambda x: 1 if x["asin_first_arrival_time"] == x["first_arrival_time"] and x[
                    "asin_first_arrival_time"] != None and x["first_arrival_time"] != None else 0 in value, sliceData)
            )
            continue

        if "business_user_name" == conditionKey:
            value = convertValueType(condition["business_user_name"])
            sliceData = list(filter(lambda x: (1 if x["listing_person_id"] == x["business_user_id"] and x[
                "listing_person_id"] != None and x["business_user_id"] != None else 0) in value, sliceData))
            continue

        # 上架人员ID
        if "listing_person" == conditionKey:
            if sliceData:
                value = convertValueType(condition["listing_person"])["value"]
                idSet = list(set([i["listing_person_id"] for i in sliceData]))
                sql = "SELECT id, user_full_path from rb_admin WHERE id IN %s"
                userPathSet = cursorData.execute_sql_many1(sql,(idSet,))
                sliceDataTemp = list(filter(lambda x: contains(x["user_full_path"],value) ==True, userPathSet))
                idSet = [i["id"] for i in sliceDataTemp]
                sliceData = list(filter(lambda x: x["listing_person_id"] in idSet, sliceData))
            continue

        if "available_quantity" == conditionKey:
            value = convertValueType(condition["available_quantity"])
            maximum, minimum = value.get('max', float('inf')), value.get('min', float('-inf'))
            sliceData = list(
                filter(lambda x: x["quality"] != None and minimum <= x["quality"] <= maximum, sliceData))
            continue

        if "sale_price" == conditionKey:
            value = convertValueType(condition["sale_price"])
            maximum, minimum = value.get('max', float('inf')), value.get('min', float('-inf'))
            sliceData = list(
                filter(lambda x: x["sale_price"] != None and minimum <= x["sale_price"] <= maximum,
                       sliceData))
            continue

        if conditionKey in [
            "publish_time",
            "trans_to_fba_time",
            "trans_to_fba_pending_time"
        ]:
            value = convertValueType(condition[conditionKey])
            minimum, maximum = value.get('max', None), value.get('min', None)
            if type(minimum) == str or type(maximum) == str:
                maximum, minimum = minimum, maximum
            if minimum:
                if type(minimum) == int:
                    minimum = (datetime.datetime.now() + datetime.timedelta(days=-(value["max"]))).strftime("%Y-%m-%d")
                minimum = datetime.datetime.strptime(minimum + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
            else:
                minimum = datetime.datetime.min
            if maximum:
                if type(maximum) == int:
                    maximum = (datetime.datetime.now() + datetime.timedelta(days=-(value["min"]))).strftime("%Y-%m-%d")
                maximum = datetime.datetime.strptime(maximum + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
            else:
                maximum = datetime.datetime.max
            sliceData = list(
                filter(lambda x: x[conditionKey] is not None and minimum <= x[conditionKey] <= maximum, sliceData))
            continue

    tempMatchingSku = [{"source_id": i["source_id"], "msku": i["msku"], "asin": i["asin"]} for i in sliceData]
    return tempMatchingSku


def filterCondition2(sliceData, value):
    """

    @param res
    @param conditionName:
    @param condition:
    @return:
    """
    sliceData = list(filter(lambda x: x["tag_id"] in value, sliceData))
    sliceDataLis = [{"msku": i["msku"]} for i in sliceData]
    return sliceDataLis

def filterTemplateCondition(filed, sliceData, value, ids):
    """

    @param res
    @param conditionName:
    @param condition:
    @return:
    """
    sliceData = list(filter(lambda x: x[filed] in value, sliceData))
    sliceDataLis = [{ids[0]: i[ids[0]]} for i in sliceData]
    return sliceData


def filterCondition3(sliceData, value, batchData):
    """

    @param res
    @param conditionName:
    @param condition:
    @return:
    """
    maximum, minimum = value.get('max', float('inf')), value.get('min', float('-inf'))
    sliceData = list(
        filter(lambda x: minimum <= 0 if x["rating_star"] == None else x["rating_star"] <= maximum,
               sliceData))
    sliceDataLis = [i["asin"] for i in sliceData]
    sliceDataLis = list(filter(lambda x: x["asin"] in sliceDataLis, batchData))
    return sliceDataLis


def filterCondition3a(sliceData, value, sliceMskuAsinData, orderSourceId):
    """

    @param res
    @param conditionName:
    @param condition:
    @return:
    """
    sliceData = list(
        filter(lambda x: x["rating_star"] != None and value["min"] <= x["rating_star"] <= value["max"], sliceData))
    asinValue = [i["asin"] for i in sliceData]
    sliceMskuAsinData = list(filter(lambda x: x["asin"] in asinValue, sliceMskuAsinData))
    sliceMskuData = [{"source_id": orderSourceId, "msku": i["msku"]} for i in sliceMskuAsinData]
    return sliceMskuData


def filterCondition4(tempList, matchingSkuId):
    if matchingSkuId:
        tempList = [i["msku"] for i in tempList]
        sliceData = list(filter(lambda x: x["msku"] in tempList, matchingSkuId))
    else:
        sliceData = tempList
    return sliceData


def filterCondition5(tempList, matchingSkuId):
    """

    @param res
    @param conditionName:
    @param condition:
    @return:
    """
    if matchingSkuId:
        sliceData = list(filter(lambda x: x["asin"] in tempList, matchingSkuId))
    else:
        sliceData = tempList
    return sliceData


def filterCondition6(tempList, matchingSkuId):
    """

    @param res
    @param conditionName:
    @param condition:
    @return:
    """
    if matchingSkuId:
        tempList = [i["order_source_sku"] for i in tempList]
        sliceData = list(filter(lambda x: x["msku"] in tempList, matchingSkuId))
    else:
        sliceData = tempList
    return sliceData


def getQueryFiled(customParam):
    filed = []
    if customParam == 0:
        filed.append("seven_day_sale_num")
    if customParam == 1:
        filed.append("fourteen_day_sale_num")
    if customParam == 2:
        filed.append("thirty_day_sale_num")
    if customParam == 3:
        filed.append("ninety_day_sale_num")
    return filed


def filterOrderConditionInit(orderSourceId, filedType, listingId, templateRuleValue, cursorListing, isFirst, country,
                             mark=False):
    id = getListingBaseId(orderSourceId)
    tempDataList = []
    tempMatchingSku = []
    for item in range(0, len(listingId), 1000):
        print("filedType1: " + str(item) + "-" + str((item + 1000)))
        batchData = tuple(listingId[item: item + 1000])
        if isFirst:
            if not mark:
                sliceData = getSliceOrderData(id, cursorListing, batchData, country)
                tempMatchingSku = filterOrderConditionListing1(sliceData, templateRuleValue)
            else:
                batchData = getOrderOtherListingSkuData(cursorListing, id, batchData)
                sliceData = getAggregateData(orderSourceId, cursorListing, batchData, filedType)
                sliceData = getDictMerge(sliceData, batchData)
                tempMatchingSku = filterOrderConditionListing2(sliceData, templateRuleValue, filedType)
        else:
            sliceData = getAggregateData(orderSourceId, cursorListing, batchData, filedType)
            sliceData = getDictMerge(sliceData, batchData)
            tempMatchingSku = filterOrderConditionListing2(sliceData, templateRuleValue, filedType)
        tempDataList += tempMatchingSku
    return tempDataList


def getDictMerge(a, b):
    for i in a:
        for x in b:
            if i["msku"] == x["msku"]:
                i["sku"] = x["sku"]
    return a


def getDateBase(condition):
    conditionName = condition["condition_field"]
    dateBase = ""
    if conditionName == "company_first_order_time_num":
        dateBase = "rb_first_order_sku"
    if conditionName == "platform_first_order_time_num":
        dateBase = "t_amazon_listing_extra_sys_sku"
    if conditionName == "platform_site_first_order_time_num":
        dateBase = "t_amazon_listing_extra_sys_sku_country"
    if conditionName == "country_first_order_time_num":
        dateBase = "rb_first_order_country"
    if conditionName == "asin_first_order_time_num":
        dateBase = "asin_first_order_time"
    if conditionName == "channel_sku_first_order_time_num":
        dateBase = "first_order_time"
    return dateBase


def filterOrderOtherConditionInit(orderSourceId, condition, listingId, cursorListing, orderCursor, isFirst, country):
    tempDataList = []
    tempMatchingSku = []
    id = getListingBaseId(orderSourceId)
    dateBase = getDateBase(condition)
    customParam = json.loads(condition["condition_value"])["customParam"]
    conditionValue = json.loads(condition["condition_value"])
    # for item in range(0, 1, 1): # 调试代码行
    for item in range(0, len(listingId), 1000):
        # batchData = tuple(listingId[1: 3])   # 调试代码行
        batchData = tuple(listingId[item: item + 1000])
        if isFirst:
            if dateBase == "asin_first_order_time" or dateBase == "first_order_time":
                sliceData = getListingOrderData(cursorListing, id, batchData, dateBase, customParam, isFirst)
            elif dateBase == "t_amazon_listing_extra_sys_sku" or dateBase == "t_amazon_listing_extra_sys_sku_country":
                sliceDataId = getOrderOtherListingSkuData(cursorListing, id, batchData)
                sliceData = getListingFirstOrderData(cursorListing, country, batchData, dateBase, customParam)
            else:
                sliceDataId = getOrderOtherListingSkuData(cursorListing, id, batchData)
                sliceData = getListingOrderOtherData(orderCursor, dateBase, customParam, sliceDataId)
            if sliceData:
                minimum, maximum = conditionValue.get('min', '-INF'), conditionValue.get('max', 'INF')
                tempMatchingSku = getTemplateOrderData(
                    orderCursor, orderSourceId, sliceData, dateBase, minimum, maximum
                )
        else:
            if   dateBase == "first_order_time" :
                sliceData = getListingOrderData(cursorListing, id, batchData, dateBase, customParam, isFirst)
            elif dateBase == "t_amazon_listing_extra_sys_sku" or dateBase == "t_amazon_listing_extra_sys_sku_country":
                sliceData = getListingFirstOrderData(cursorListing, country, batchData, dateBase, customParam)
            elif dateBase == "asin_first_order_time":
                sliceData = getAsinData(id, cursorListing, batchData)
                sliceData = getListingAsinFirstOrderData(cursorListing, country, sliceData, customParam)
            else:
                sliceData = getListingOrderOtherData(orderCursor, dateBase, customParam, batchData, country)
            if sliceData:
                minimum, maximum = conditionValue.get('min', '-POW(10, 308)'), conditionValue.get('max', 'POW(10, 308)')
                tempMatchingSku = getTemplateOrderData(
                    orderCursor, orderSourceId, sliceData, dateBase, minimum, maximum
                )
        tempDataList += tempMatchingSku
    return tempDataList


def filterConditionInit(id, orderSourceId, listingId, templateRuleValue, cursorListing):
    tempDataList = []
    dataCursor = connectMysql("Java_strategyData")
    country = getSourceCountry(dataCursor, orderSourceId)
    for item in range(0, len(listingId), 1000):
        print("filedType: " + str(item) + "-" + str((item + 1000)))
        batchData = tuple(listingId[item: item + 1000])

        sliceData = getSliceOrderData(id, cursorListing, batchData, country, mark=False)
        tempMatchingSku = filterFbaCondition(sliceData, templateRuleValue)
        tempDataList += tempMatchingSku

    return tempDataList


def filterOtherConditionInit(orderSourceId, rule, listingId, cursorWareHouse, cursorListing, isFirst):
    id = getListingBaseId(orderSourceId)
    rule, ruleName = [rule], list(rule.keys())[0]
    sliceData = []

    if ruleName not in ["fba_inventory"]:
        tempList = []

        for item in range(0, len(listingId), 1000):
            print("filedTypeOther: " + str(item) + "-" + str((item + 1000)))
            batchData = tuple(listingId[item: item + 1000])

            if isFirst:
                mSkuData = getSliceOrderSourceSkuData(id, cursorListing, batchData)
                mSkuData = tuple([i["msku"] for i in mSkuData])
            else:
                mSkuData = tuple([item["msku"] for item in batchData])

            if ruleName in ["receiving_time"]:
                templateData = getFbaListingData(orderSourceId, cursorWareHouse, mSkuData)
                sliceData = filterFbaCondition(templateData, rule)
            elif ruleName in ["estimate_sale_num", "available_day"]:
                templateData = getWarehouseFbaListingData(cursorWareHouse, orderSourceId, mSkuData, queryFiled=[ruleName])
                sliceData = filterFbaListingCondition(templateData, rule)
            elif ruleName in ["inventory_age"]:
                customParam = eval(rule[0]["inventory_age"])["customParam"]
                queryFiled = getFbaInventoryAgeField(customParam)
                templateData = getFbaListingInventoryData(orderSourceId, cursorWareHouse, mSkuData, queryFiled)
                sliceData = filterFbaListingCondition(templateData, rule, queryFiled)

            tempList += sliceData
        sliceData = tempList

    else:
        tempList = []
        customParam = eval(rule[0]["fba_inventory"])["customParam"]
        queryFiled = getFbaInventoryAgeField2(customParam)

        for item in range(0, len(listingId), 1000):
            print("filedTypeOther: " + str(item) + "-" + str((item + 1000)))
            sliceData = tuple(listingId[item: item + 1000])
            tempQueryFiled = ["quality"]
            if not isFirst:
                sliceData = tuple([item["msku"] for item in sliceData])
            templateData = getSubmeterListingData(cursorListing, id, sliceData, tempQueryFiled, isFirst)

            if 0 in customParam:
                sliceData = filterFbaListingCondition(templateData, rule, tempQueryFiled)
                if 1 in customParam or 2 in customParam:
                    batchData = tuple([item["msku"] for item in sliceData])
                    templateData = getWarehouseFbaListingData(cursorWareHouse, orderSourceId, batchData, queryFiled)
                    sliceData = filterFbaListingCondition(templateData, rule, queryFiled)
            elif 1 in customParam or 2 in customParam:
                batchData = tuple([item["msku"] for item in templateData])
                templateData = getWarehouseFbaListingData(cursorWareHouse, orderSourceId, batchData, queryFiled)
                sliceData = filterFbaListingCondition(templateData, rule, queryFiled)

            tempList += sliceData
            sliceData = tempList

    return sliceData


def filterFbaListingCondition(sliceData, templateRuleValue, queryFiled=None):
    for condition in templateRuleValue:
        if "wait_to_fba_type" in condition.keys():
            value = condition["wait_to_fba_type"]
            sliceData = list(filter(lambda x: x["wait_to_fba_type"] in value, sliceData))
            continue
        else:
            conditionName = list(condition.keys())[0]
            value = condition[conditionName]
            if type(value) == str: value = json.loads(value)
            maximum, minimum = value.get('max', float('inf')), value.get('min', float('-inf'))
            if "profit_rate" == conditionName:
                sliceData = list(filter(
                    lambda x: x["month_avg_profits"] != None and minimum <= x["month_avg_profits"] <= maximum,sliceData)
                )
                continue
            if "estimate_sale_num" == conditionName:
                sliceData = list(
                    filter(
                        lambda x: x["estimate_sale_num"] != None and minimum <= float(x["estimate_sale_num"]) <= maximum,sliceData)
                )
                continue

            if "available_day"  == conditionName:
                sliceData = list(
                    filter(lambda x: x["available_day"] != None and minimum <= x["available_day"] <= maximum,
                           sliceData))
                continue

            if "fba_inventory" == conditionName:
                if "quality" in queryFiled:
                    sliceData = list(
                        filter(lambda x: x["quality"] != None and minimum <= x["quality"] <= maximum, sliceData))
                if "quantity_local_intransit" in queryFiled:
                    sliceData = list(filter(
                        lambda x: x["quantity_local_intransit"] != None and minimum <= x["quantity_local_intransit"] <=
                                  maximum, sliceData))
                if "quantity_oversea_intransit" in queryFiled:
                    sliceData = list(filter(lambda x: x["quantity_oversea_intransit"] != None and minimum <= x[
                        "quantity_oversea_intransit"] <= maximum, sliceData))
                continue

            if "inventory_age" == conditionName:
                if "inventory_age_0_to_30_days" in queryFiled:
                    sliceData = list(filter(lambda x: x["inventory_age_0_to_30_days"] != None and minimum <= x[
                        "inventory_age_0_to_30_days"] <= maximum, sliceData))
                if "inventory_age_31_to_60_days" in queryFiled:
                    sliceData = list(filter(lambda x: x["inventory_age_31_to_60_days"] != None and minimum <= x[
                        "inventory_age_31_to_60_days"] <= maximum, sliceData))
                if "inventory_age_61_to_90_days" in queryFiled:
                    sliceData = list(filter(lambda x: x["inventory_age_61_to_90_days"] != None and minimum <= x[
                        "inventory_age_61_to_90_days"] <= maximum, sliceData))
                if "inventory_age_91_to_180_days" in queryFiled:
                    sliceData = list(filter(lambda x: x["inventory_age_91_to_180_days"] != None and minimum <= x[
                        "inventory_age_91_to_180_days"] <= maximum, sliceData))
                if "inventory_age_181_to_270_days" in queryFiled:
                    sliceData = list(filter(lambda x: x["inventory_age_181_to_270_days"] != None and minimum <= x[
                        "inventory_age_181_to_270_days"] <= maximum, sliceData))
                if "inventory_age_271_to_365_days" in queryFiled:
                    sliceData = list(filter(lambda x: x["inventory_age_271_to_365_days"] != None and minimum <= x[
                        "inventory_age_271_to_365_days"] <= maximum, sliceData))
                if "inventory_age_365_plus_days" in queryFiled:
                    sliceData = list(filter(lambda x: x["inventory_age_365_plus_days"] != None and minimum <= x[
                        "inventory_age_365_plus_days"] <= maximum, sliceData))
                continue

    return sliceData


def filterFbaCondition(sliceData, templateRuleValue):
    # if list(filter(lambda x: x["msku"] == "20814EDBZY58GFQMMJAVJ", sliceData)):
    #     print("进来")
    for condition in templateRuleValue:
        conditionName = list(condition.keys())[0]
        value = eval(condition[conditionName])
        minimum, maximum = value.get('max', None), value.get('min', None)
        if type(minimum) == str or type(maximum) == str:
            maximum, minimum = minimum, maximum
        if minimum:
            if type(minimum) == int:
                minimum = (datetime.datetime.now() + datetime.timedelta(days=-(value["max"]))).strftime("%Y-%m-%d")
            minimum = datetime.datetime.strptime(minimum + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
        else:
            minimum = datetime.datetime.min
        if maximum:
            if type(maximum) == int:
                maximum = (datetime.datetime.now() + datetime.timedelta(days=-(value["min"]))).strftime("%Y-%m-%d")
            maximum = datetime.datetime.strptime(maximum + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
        else:
            maximum = datetime.datetime.max
        if conditionName in [
            "first_arrival_time",
            "asin_first_arrival_time",
            "receiving_time"
        ]:
            sliceData = list(filter(lambda x: x[conditionName] != None and minimum <= x[conditionName] <= maximum,sliceData))
    sliceData = [{"source_id": i["source_id"], "msku": i["msku"]} for i in sliceData]
    return sliceData


def filterOrderConditionListing1(sliceData, templateRuleValue):
    for condition in templateRuleValue:
        conditionName = condition["condition_field"]
        if conditionName in [
            "asin_first_order_time",
            "first_order_time"
        ]:
            value = eval(condition["condition_value"])
            minimum, maximum = value.get('max', None), value.get('min', None)
            if type(minimum) == str or type(maximum) == str:
                maximum, minimum = minimum, maximum
            if minimum:
                if type(minimum) == int:
                    minimum = (datetime.datetime.now() + datetime.timedelta(days=-(value["max"]))).strftime("%Y-%m-%d")
                minimum = datetime.datetime.strptime(minimum + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
            else:
                minimum = datetime.datetime.min
            if maximum:
                if type(maximum) == int:
                    maximum = (datetime.datetime.now() + datetime.timedelta(days=-(value["min"]))).strftime("%Y-%m-%d")
                maximum = datetime.datetime.strptime(maximum + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
            else:
                maximum = datetime.datetime.max
            sliceData = list(filter(lambda x: x[conditionName] != None and minimum <= x[conditionName] <= maximum,sliceData))
    sliceData = [{"source_id": i["source_id"], "sku": i["sku"], "msku": i["msku"]} for i in sliceData]
    return sliceData


def filterOrderConditionListing2(sliceData, templateRuleValue, filedType=None):
    for condition in templateRuleValue:
        conditionName = condition["condition_field"]
        if conditionName == "sale_num":
            value = eval(condition["condition_value"])
            maximum, minimum = value.get('max', float('inf')), value.get('min', float('-inf'))
            if "seven_day_sale_num" in filedType:
                sliceData = list(filter(
                    lambda x: x["seven_day_sale_num"] != None and minimum <= x["seven_day_sale_num"] <= maximum, sliceData))
                continue
            if "fourteen_day_sale_num" in filedType:
                sliceData = list(filter(
                    lambda x: x["fourteen_day_sale_num"] != None and minimum <= x["fourteen_day_sale_num"] <= maximum, sliceData))
                continue
            if "thirty_day_sale_num" in filedType:
                sliceData = list(filter(
                    lambda x: x["thirty_day_sale_num"] != None and minimum <= x["thirty_day_sale_num"] <= maximum, sliceData))
                continue
            if "ninety_day_sale_num" in filedType:
                sliceData = list(filter(
                    lambda x: x["ninety_day_sale_num"] != None and minimum <= x["ninety_day_sale_num"] <= maximum, sliceData))
                continue
    sliceData = [{"source_id": i["source_id"], "sku": i["sku"], "msku": i["msku"]} for i in sliceData]
    return sliceData


def logicFbaDispose1(sliceData, templateRuleValueOther):
    for condition in templateRuleValueOther:
        conditionName = list(condition.keys())[0]
        value = eval(condition[conditionName])
        minimum = (datetime.datetime.now() + datetime.timedelta(days=-(value["max"]))).strftime("%Y-%m-%d")
        maximum = (datetime.datetime.now() + datetime.timedelta(days=-(value["min"]))).strftime("%Y-%m-%d")
        minimum = datetime.datetime.strptime(minimum + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
        maximum = datetime.datetime.strptime(maximum + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
        if "receiving_time" in condition.keys():
            sliceData = list(
                filter(lambda x: x["receiving_time"] != None and minimum <= x["receiving_time"] <= maximum, sliceData))
        sliceData = [{"source_id": i["source_id"], "msku": i["msku"]} for i in sliceData]
    return sliceData


def logicDispose(res, conditionName, condition):
    """

    @param res:
    @param conditionName:
    @param condition:
    @return:
    """
    tempMatchingSku = ()
    conditionValue = eval(condition["condition_value"])["value"]
    conditionValue = convertValueType(conditionValue)
    conditionName = convertFiled(conditionName)
    if type(conditionName) == str:
        for data in res:
            templateValue = data[conditionName]
            if templateValue in conditionValue:
                tempMatchingSku += ((data["source_id"], data["msku"]),)
    else:
        for data in res:
            templateValue = 0
            if data[conditionName[0]] == data[conditionName[1]]:
                templateValue = 1
            if templateValue in conditionValue:
                tempMatchingSku += ((data["source_id"], data["msku"]),)
    return tempMatchingSku


def logicDispose2(res, conditionName, condition):
    """

    @param res:
    @param conditionName:
    @param condition:
    @return:
    """
    tempMatchingSku = ()
    if "min" in condition["condition_value"] and "max" in condition["condition_value"]:
        maximum = eval(condition["condition_value"])["max"]
        minimum = eval(condition["condition_value"])["min"]
        conditionName = convertFiled(conditionName)
        for data in res:
            if data[conditionName]:
                if minimum <= data[conditionName] <= maximum:
                    tempMatchingSku += ((data["source_id"], data["msku"]),)
    elif "min" in condition["condition_value"] and "max" not in condition["condition_value"]:
        minimum = eval(condition["condition_value"])["min"]
        conditionName = convertFiled(conditionName)
        for data in res:
            if data[conditionName]:
                if minimum <= data[conditionName]:
                    tempMatchingSku += ((data["source_id"], data["msku"]),)
    else:
        maximum = eval(condition["condition_value"])["max"]
        conditionName = convertFiled(conditionName)
        for data in res:
            if data[conditionName]:
                if data[conditionName] <= maximum:
                    tempMatchingSku += ((data["source_id"], data["msku"]),)

    return tempMatchingSku


def logicDispose3(res, conditionName, condition):
    """

    @param res:
    @param conditionName:
    @param condition:
    @return:
    """
    tempMatchingSku = []
    if "min" in condition["condition_value"] and "max" in condition["condition_value"]:
        minimum = eval(condition["condition_value"])["max"]
        maximum = eval(condition["condition_value"])["min"]
        if "-" not in str(maximum):
            minimum = (datetime.datetime.now() + datetime.timedelta(days=-minimum)).strftime("%Y-%m-%d")
            maximum = (datetime.datetime.now() + datetime.timedelta(days=-maximum)).strftime("%Y-%m-%d")
        minimum = datetime.datetime.strptime(minimum + ' 00:00:00', '%Y-%m-%d %H:%M:%S')
        maximum = datetime.datetime.strptime(maximum + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
        conditionName = convertFiled(conditionName)
        for data in res:
            if data[conditionName]:
                if minimum <= data[conditionName] <= maximum:
                    tempMatchingSku += ((data["source_id"], data["msku"]),)
    elif "min" in condition["condition_value"] and "max" not in condition["condition_value"]:
        minimum = eval(condition["condition_value"])["min"]
        if "-" not in str(minimum):
            minimum = (datetime.datetime.now() + datetime.timedelta(days=-minimum)).strftime("%Y-%m-%d")
        minimum = datetime.datetime.strptime(minimum, '%Y-%m-%d')
        conditionName = convertFiled(conditionName)
        for data in res:
            if data[conditionName]:
                if minimum <= data[conditionName]:
                    tempMatchingSku += ((data["source_id"], data["msku"]),)
    else:
        maximum = eval(condition["condition_value"])["max"]
        if "-" not in str(maximum):
            maximum = (datetime.datetime.now() + datetime.timedelta(days=-maximum)).strftime("%Y-%m-%d")
        maximum = datetime.datetime.strptime(maximum, '%Y-%m-%d')
        conditionName = convertFiled(conditionName)
        for data in res:
            if data[conditionName]:
                if data[conditionName] <= maximum:
                    tempMatchingSku += ((data["source_id"], data["msku"]),)

    return tempMatchingSku


def getFbaInventoryAgeField(customParam):
    filedType = []
    for i in customParam:
        if i == 0:
            filedType.append("inventory_age_0_to_30_days")
        elif i == 1:
            filedType.append("inventory_age_31_to_60_days")
        elif i == 2:
            filedType.append("inventory_age_61_to_90_days")
        elif i == 3:
            filedType.append("inventory_age_91_to_180_days")
        elif i == 4:
            filedType.append("inventory_age_181_to_270_days")
        elif i == 5:
            filedType.append("inventory_age_271_to_365_days")
        elif i == 6:
            filedType.append("inventory_age_365_plus_days")
    return filedType


def getFbaInventoryAgeField2(customParam):
    filedType = []
    for i in customParam:
        if i == 1:
            filedType.append("quantity_local_intransit")
        elif i == 2:
            filedType.append("quantity_oversea_intransit")
    return filedType


def getFbaInventoryAgeField3(customParam):
    filedType = []
    if customParam == 0:
        filedType.append("seven_day_sale_num")
    elif customParam == 1:
        filedType.append("fourteen_day_sale_num")
    elif customParam == 2:
        filedType.append("thirty_day_sale_num")
    elif customParam == 3:
        filedType.append("ninety_day_sale_num")
    return filedType


def getListingTypeTemplatecondition(filedName):
    filed = [
        "online_status",
        "delivery_type",
        "listing_method",
        "fba_new",
        "business_user_name",
        "listing_person",
        "available_quantity",
        "sale_price",
        "publish_time",
        "trans_to_fba_time",
        "trans_to_fba_pending_time"
    ]
    if filedName in filed:
        return True
    else:
        return False


def getListingTypeTemplateconditionOther(filedName):
    filed = [
        "profit_rate",
        "wait_to_fba_state"
    ]
    if filedName in filed:
        return True
    else:
        return False


def getSubmeterListingDataID(cursor, id, orderSourceId):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """

    sql = f"SELECT id,customer_id,is_deleted FROM " \
          f"t_amazon_listing_{id} WHERE source_id = {orderSourceId};"
    res = cursor.execute_sql_many(sql)
    res = list(filter(lambda x: x["customer_id"] == 1 and x["is_deleted"] == 0, res))
    resList = [item["id"] for item in res]
    return resList

def getSubmeterListingId(cursor, id, orderSourceId):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """

    sql = f"SELECT id, customer_id, is_deleted FROM " \
          f"t_amazon_listing_{id} WHERE source_id = {orderSourceId};"
    res = cursor.execute_sql_many(sql)
    res = list(filter(lambda x: x["customer_id"] == 1 and x["is_deleted"] == 0, res))
    resList = [item["id"] for item in res]
    return resList


def getSubmeterSKUData(cursor, id, orderSourceId):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """

    sql = f"SELECT sku,customer_id,is_deleted FROM " \
          f"t_amazon_listing_{id} WHERE source_id = {orderSourceId};"
    res = cursor.execute_sql_many(sql)
    res = list(filter(lambda x: x["customer_id"] == 1 and x["is_deleted"] == 0, res))
    resList = list(set([item["sku"] for item in res]))
    return resList


# 分表获取Listing数据
def getSubmeterListingSkuData(cursor, id, orderSourceId):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    sql = f"SELECT source_id, sku, msku, country FROM " \
          f"t_amazon_listing_{id} WHERE customer_id = 1 AND is_deleted = 0 AND source_id = {orderSourceId}"
    res = cursor.execute_sql_many(sql)
    return res


def getSubmeterListingData2(cursor, id, orderSourceId, conditionName, customParam):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    condition = []
    condition.append(conditionName)
    filed = ','.join(condition)
    sql = f"SELECT source_id, msku, {filed},  DATE_ADD({filed}, INTERVAL {customParam} DAY) AS {filed}_end FROM " \
          f"t_amazon_listing_{id} WHERE customer_id = 1 AND is_deleted = 0 AND source_id = {orderSourceId}"
    res = cursor.execute_sql_many(sql)
    return res


def getSubmeterListingData3(cursor, orderSourceId, data, conditionName, maximum, minimum):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    orderSourceSku = data["msku"]
    res = []
    if data[conditionName]:
        starTime = data[conditionName].strftime('%Y-%m-%d')
        endTime = data[conditionName + "_end"].strftime('%Y-%m-%d')

        sql = f"SELECT order_source_id, order_source_sku, sum(order_num) AS sum " \
              f"FROM rb_report_order_source_sku_day " \
              f"WHERE customer_id = 1 AND order_source_id = {orderSourceId} AND order_source_sku = '{orderSourceSku}' " \
              f"AND sales_day BETWEEN '{starTime}' AND '{endTime}' " \
              f"GROUP BY order_source_id, order_source_sku"
        res = cursor.execute_sql_many(sql)
    if res:
        if minimum <= res[0]["sum"] <= maximum:
            res = [(orderSourceId, data["msku"])]
        else:
            res = []
    return res


def getListingSaleNumData(cursor, orderSourceId, condition):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """

    filed = ','.join(condition)
    sql = f"SELECT source_id, msku, {filed} FROM " \
          f"t_amazon_sales_aggregate WHERE customer_id = 1 AND source_id = {orderSourceId}"
    res = cursor.execute_sql_many(sql)
    return res


# def getListingOrderData(cursor, dateBase, customParam):
#     """
#
#     @param cursor:
#     @param id:
#     @param orderSourceId:
#     @return:
#     """
#
#     sql = f"SELECT sku, first_order_time, DATE_ADD(first_order_time, INTERVAL {customParam} DAY) AS first_order_time_end FROM " \
#           f"{dateBase} WHERE customer_id = 1 AND is_delete = 0 "
#     res = cursor.execute_sql_many(sql)
#     return res


def getListingOrderData2(cursor, dateBase, customParam, listingSkuRes):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    res = []
    for i in listingSkuRes:
        sku = i["sku"]
        if sku:
            # print(i)
            sql = f"SELECT sku, first_order_time, DATE_ADD(first_order_time, INTERVAL {customParam} DAY) AS first_order_time_end FROM " \
                  f"{dateBase} WHERE customer_id = 1 AND is_delete = 0 AND sku = '{i['sku']}'"
            result = cursor.execute_sql_many(sql)
            if result:
                result[0]["msku"] = i["msku"]
                print(result)
                res.append(result[0])
    return res


def getListingOrderData3(cursor, dateBase, customParam, listingSkuRes):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    res = []
    for i in listingSkuRes:
        sku = i["sku"]
        if sku:
            # print(i)
            sql = f"SELECT sku, first_order_time, DATE_ADD(first_order_time, INTERVAL {customParam} DAY) AS first_order_time_end FROM " \
                  f"{dateBase} WHERE customer_id = 1 AND is_delete = 0 AND order_source_type = 1 AND sku = '{i['sku']}'"
            result = cursor.execute_sql_many(sql)
            if result:
                result[0]["msku"] = i["msku"]
                print(result)
                res.append(result[0])
    return res


def getListingOrderData4(cursor, dateBase, customParam, listingSkuRes):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    res = []
    for i in listingSkuRes:
        sku = i["sku"]
        country = i["country"]
        if sku:
            # print(i)
            sql = f"SELECT sku, first_order_time, DATE_ADD(first_order_time, INTERVAL {customParam} DAY) AS first_order_time_end FROM " \
                  f"{dateBase} WHERE customer_id = 1 AND is_delete = 0 AND order_source_type = 1 AND country = '{country}' AND sku = '{i['sku']}'"
            result = cursor.execute_sql_many(sql)
            if result:
                result[0]["msku"] = i["msku"]
                print(result)
                res.append(result[0])
    return res


def getListingOrderData5(cursor, dateBase, customParam, listingSkuRes):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    res = []
    for i in listingSkuRes:
        sku = i["sku"]
        country = i["country"]
        if sku:
            # print(i)
            sql = f"SELECT sku, first_order_time, DATE_ADD(first_order_time, INTERVAL {customParam} DAY) AS first_order_time_end FROM " \
                  f"{dateBase} WHERE customer_id = 1 AND is_delete = 0 AND country = '{country}' AND sku = '{i['sku']}'"
            result = cursor.execute_sql_many(sql)
            if result:
                result[0]["msku"] = i["msku"]
                print(result)
                res.append(result[0])
    return res


def getHolidayListingData(cursor, id, orderSourceId):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    sql = f"SELECT t1.source_id,t1.msku,t2.tag_id " \
          f"FROM t_amazon_listing_{id} t1 JOIN t_amazon_listing_tag_{id} t2 " \
          f"ON t1.id = t2.listing_id AND t1.customer_id = t2.customer_id " \
          f"WHERE t1.customer_id = 1 AND t1.is_deleted = 0 AND t1.source_id = {orderSourceId}"
    res = cursor.execute_sql_many(sql)
    return res


def getHolidayListing(cursor, id, batchData):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    sql = f"SELECT t1.id, t1.source_id, t1.msku, t1.asin, t2.tag_id " \
          f"FROM t_amazon_listing_{id} t1 JOIN t_amazon_listing_tag_{id} t2 " \
          f"ON t1.id = t2.listing_id AND t1.customer_id = t2.customer_id " \
          f"WHERE t1.id in {batchData}"
    res = cursor.execute_sql_many(sql)
    return res


def getSubMeterListingDataMongo(orderSourceId):
    sql = {"customer_id": 1, "is_delete": 0, "order_source_id": orderSourceId}
    filed = {"order_source_id": 1, "order_source_sku": 1, "wait_to_fba_type": 1, "month_avg_profits": 1, "_id": 0}
    mongoCursor = connectMongoJava("rb_amazon_product_base")
    res = mongoCursor.select2(sql, filed)
    return res


def getSliceDataMongo(orderSourceId, batchData):
    sql = {"order_source_id": orderSourceId, "order_source_sku": {"$in": batchData}}
    filed = {"order_source_id": 1, "order_source_sku": 1, "wait_to_fba_type": 1, "month_avg_profits": 1, "_id": 0}
    mongoCursor = connectMongoTest("rb_amazon_product_base")
    res = mongoCursor.select2(sql, filed)
    return res


def getSubmeterListingHolidayTagData(cursor, id, orderSourceId):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    sql = f"SELECT t1.source_id, t1.msku, t2.tag_id " \
          f"FROM t_amazon_listing_{id} t1 JOIN t_amazon_listing_tag_{id} t2 " \
          f"ON t1.id = t2.listing_id AND t1.customer_id = t2.customer_id " \
          f"WHERE t1.customer_id = 1 AND t1.is_delete = 0 AND source_id = {orderSourceId}"
    res = cursor.execute_sql_many(sql)
    return res


def getSubmeterListingRatingStarData(cursor, id, orderSourceId):
    """

    @param cursor:
    @param id:
    @param orderSourceId:
    @return:
    """
    sql = f"SELECT t1.source_id, t1.msku, t2.rating_star " \
          f"FROM t_amazon_listing_{id} t1 JOIN t_amazon_listing_extra_{id} t2 " \
          f"ON t1.asin = t2.asin AND t1.customer_id = t2.customer_id " \
          f"WHERE t1.customer_id = 1 AND t1.is_delete = 0 AND source_id = {orderSourceId}"
    res = cursor.execute_sql_many(sql)
    return res


# 获取亚马逊有效来源渠道id
def getCountryOrderSourceId(cursor, isCountry=True):
    """

    @param isCountry:
    @return:
    """
    sourceId = [6891]
    return sourceId


def mSkuConvertSku(id, orderSourceId, appointType, appoints, cursorListing):
    SkuSet = []
    for item in range(0, len(appoints), 1000):
        batchData = tuple(appoints[item: item + 1000])
        if len(batchData) == 1:
            batchData = f"('{batchData[0]}')"
        if appointType == 2:
            tempSkuSet = getMSkuConvertSku(
                id, orderSourceId, cursorListing, batchData, IsMSku=True
            )
        else:
            tempSkuSet = getMSkuConvertSku(
                id, orderSourceId, cursorListing, batchData, IsMSku=False
            )
        SkuSet += tempSkuSet
    return SkuSet


def getProductStrategySku(productStrategyId, sku_set):
    tempSpecifySkuSet = []

    for id in productStrategyId:
        id = int(id)
        for i in range(0, len(sku_set), 1000):
            batchData = sku_set[i: i + 1000]
            comparison = {"sql": {"strategy_relation.strategy_id": id, "sku": {"$in":batchData}}, "field": {"_id": 0, "sku": 1}}
            tempSkuSet = getStrategyResult(comparison, id)
            tempSkuSet = [i["sku"] for i in tempSkuSet]
            tempSpecifySkuSet += tempSkuSet
    return tempSpecifySkuSet


def getSourceAllSku(baseId, listingId, cursorListing):
    temp = []
    for id in range(0, len(listingId), 1000):
        batchData = tuple(listingId[id: id + 1000])
        print(str(id) + "-" + str(id + 1000))
        if len(batchData) == 1:
            tempBatchData = f"('{batchData[0]}')"
            listingSku = getTemplateListingSku(cursorListing, baseId, tempBatchData)
        else:
            listingSku = getTemplateListingSku(cursorListing, baseId, batchData)
        temp += listingSku
    return temp


def getNoSaleData(cursorProduct, batchData, sourceCountry, platformNoSale):
    if len(batchData) == 1:
        tempBatchData = f"('{batchData[0]}')"
        tempList = productNoSaleJudge(cursorProduct, tempBatchData)
    else:
        tempList = productNoSaleJudge(cursorProduct, batchData)
    noSaleData = list(
        filter(lambda x: x["country_shorthand"] == '' or x["country_shorthand"] == sourceCountry, tempList))
    noSaleData = [x["sku"] for x in noSaleData]
    # 不禁售
    if platformNoSale == 1:
        batchData = tuple(list(filter(lambda x: x not in noSaleData, batchData)))
    # 禁售
    else:
        batchData = tuple(list(filter(lambda x: x in noSaleData, batchData)))
    return batchData


def getHighRiskLevelData(cursorProduct, batchData, sourceCountry, productRiskLevel):
    if len(batchData) == 1:
        tempBatchData = f"('{batchData[0]}')"
        tempList = getProductRiskLevelJudge(cursorProduct, tempBatchData)
    else:
        tempList = getProductRiskLevelJudge(cursorProduct, batchData)
    highRiskData = list(
        filter(lambda x: x["country_shorthand"] == None or x["country_shorthand"] == sourceCountry, tempList))
    # 高危
    if productRiskLevel == 1:
        batchData = tuple(list(filter(lambda x: x in highRiskData, batchData)))
    # 普通
    else:
        batchData = tuple(list(filter(lambda x: x not in highRiskData, batchData)))
    return batchData

def TemplateRuleDataPolymerization(cursorStrategy, orderSourceId, strategyRule, isFbaFilter, sourceCountry):
    listingDataList = []
    isFirst = True
    isFbaFilter = isFbaFilter[0].get("fbm_template_id", None)
    for rule in strategyRule:
        listingId = []
        templateId = json.loads(rule["template_ids"])
        if len(templateId) > 1:
            count_list = getTemplateCount(cursorStrategy, templateId)
            sorted_list = sorted(count_list, key=lambda x: x["bind_count"])
            templateIsFirst = True
            for num in sorted_list:
                tempListingId = []
                if templateIsFirst and isFirst:
                    listingId = getTemplateListingDataTrue(num["id"], orderSourceId, isFbaFilter)
                    templateIsFirst = False
                    continue
                temp_listing = [i["listing_id"] for i in listingId]
                for id in range(0, len(temp_listing), 1000):
                    listing = getTemplateListingDataFalse(num["id"], temp_listing[id: id + 1000])
                    if isFbaFilter:
                        filterTemplate = isFbaFilter
                        listing = getSameAsinCountryListing(listing, filterTemplate, sourceCountry)
                    tempListingId += listing
                listingId = tempListingId
            listingDataList += listingId
        else:
            listingId = getTemplateListingDataTrue(templateId[0], orderSourceId, isFbaFilter)
            if isFbaFilter:
                filterTemplate = isFbaFilter
                listingId = getSameAsinCountryListing(listingId, filterTemplate, sourceCountry)
            # 按规则维度判断是否存在同国家同ASIN的Listing
            listingDataList += listingId
    return listingDataList

def StrategyRuleDataPolymerization(strategyID, orderSourceId, skuSet):
    listingDataList = []
    for id in range(0, len(skuSet), 1000):
        batchData = skuSet[id: id + 1000]
        listing = getStrategyListingData(strategyID, orderSourceId, batchData)
        listingDataList += listing
    return listingDataList






if __name__ == '__main__':
    lis = [14675]
    for i in lis:
        res = getListingBaseId(i)
        print(res)
